package com.taurus.permanent.normal;

import java.nio.channels.DatagramChannel;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

public class DatagramChannelCache {
	private final ConcurrentMap<Integer, DatagramChannel[]> udpChannelCache;

	private final int cacheSize;

	private final AtomicInteger indexer;

	public DatagramChannelCache(int cacheSize) {
		this.udpChannelCache = new ConcurrentHashMap<>();
		this.cacheSize = cacheSize;
		this.indexer = new AtomicInteger(0);
	}

	public void addChannels(int port, DatagramChannel[] channels) {
		if (channels.length > this.cacheSize)
			throw new IllegalArgumentException(
					"Inconsistent cache state. Expected size:  " + this.cacheSize + ", found: " + channels.length);
		if (this.udpChannelCache.containsKey(Integer.valueOf(port)))
			throw new IllegalStateException("UDP Port " + port + " is already bound");
		this.udpChannelCache.put(Integer.valueOf(port), channels);
	}

	public DatagramChannel getChannelForPort(int port) {
		DatagramChannel[] channels = this.udpChannelCache.get(Integer.valueOf(port));
		DatagramChannel chan = null;
		if (channels != null) {
			int id = this.indexer.updateAndGet(value -> (value >= this.cacheSize - 1) ? 0 : (value + 1));
			chan = channels[id];
		}
		return chan;
	}
}
